package com.xiaoxiong.text;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HttpClientText extends Activity implements OnClickListener {

	private final static int SUCCESS = 1;
	private final static int FAILE = 0;
	private TextView result;
	private Button send;
	private LoadingDialog loadingDialog;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initData();
	}

	private void initData() {
		mContext = this;
		result = (TextView) findViewById(R.id.result);
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(this);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			String response;
			if(loadingDialog != null && loadingDialog.isShowing()){
				loadingDialog.dismiss();
			}
			switch (msg.what) {
			case SUCCESS:
				response = msg.obj.toString();
				result.setText(response);
				break;
			case FAILE:
				response = msg.obj.toString();
				result.setText(response);
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send:
			loadingDialog = new LoadingDialog(mContext);
			loadingDialog.setCancel(false);
			loadingDialog.show();
			startSend();
			break;
		}
	}

	private void startSend() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					//因为HttpClient是一个接口，所以用DefaultHttpClient()方法创建一个实例
					HttpClient httpClient = new DefaultHttpClient();
					//创建HttpGet对象并传入网络地址，并调用HttpClient的execute方法发送GET请求
					HttpGet httpGet = new HttpGet("http://www.baidu.com");
					HttpResponse httpResponse = httpClient.execute(httpGet);
					//先取出服务器返回的状态码，如果是200则说明请求响应成功，这里可以自行判断获得的状态码
					//是什么来判断是否成功或是什么失败
					if(httpResponse.getStatusLine().getStatusCode() == 200){
						//请求响应成功,调用getEntity()方法获取HttpEntity实例并转换成字符串
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");

						//获取成功，发送成功信息
						Message message = new Message();
						message.what = SUCCESS;
						message.obj = response;
						mHandler.sendMessage(message);
					}
				} catch (Exception e) {
					//发送失败信息
					Message message = new Message();
					message.what = FAILE;
					message.obj = "请求失败";
					mHandler.sendMessage(message);
					e.printStackTrace();
				}
			}

		}).start();
	}

}
